package com.wlyuan.open.scanner.application.handler.incr;

import com.wlyuan.open.dto.OpenCarrierSyncDTO;
import com.wlyuan.open.scanner.assembler.ScannerCarrierAssembler;
import com.wlyuan.open.scanner.constant.ScannerCodeEnum;
import com.wlyuan.open.scanner.repository.CarrierRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Optional;

/**
 * @author lijing
 * @description 线上承运方 增量 listener
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CarrierOnlineIncrHandler extends BaseIncrHandler<OpenCarrierSyncDTO> {
    private final CarrierRepository carrierRepository;

    @Override
    public OpenCarrierSyncDTO process(Long supplierId) {
        logger.info("线上承运方增量：{}", supplierId);
        return Optional.ofNullable(supplierId).map(id -> {
            var supplier = carrierRepository.getOnline(id);
            return ScannerCarrierAssembler.assemble(supplier);
        }).orElse(null);
    }

    @Override
    public void incrByTenantId(Long tenantId) {
        carrierRepository.getOnlineTenantId(tenantId);
    }

    @Override
    public void incrByTime(Long tenantId, String startTime, String endTime) {
        var list = tenantId == null ? carrierRepository.getOnlineByTime(startTime, endTime) : carrierRepository.getOnlineTenantIdByTime(tenantId, startTime, endTime);
        if (CollectionUtils.isEmpty(list)) {
            logger.info("根据时间{},{}数据为0", startTime, endTime);
            return;
        }
        logger.info("根据时间{},{}数据为：{}", startTime, endTime, list.size());
        list.parallelStream().forEach(id -> increment(id));
        logger.info("同步完成");
    }

    @Override
    public String getSyncType() {
        return ScannerCodeEnum.CARRIER_ONLINE.getVal();
    }
}
